$(function(){
    $("#input_device_id").val(searchDeviceId());    
    $("#input_device_name").val(setting_data.name);
    $("#input_device_type").val(setting_data.type)
    $("#input_device_address").val(setting_data.address);
    $("#input_device_second").val(setting_data.second);
    $("#input_device_state").val(setting_data.status);
    setDescription(setting_data.description);  
    setSensor_list(setting_data.monitor_limit);

    $.ajax({
        type: "GET",
        url: "/index/get_user_list/", // data: JSON.stringify(json), contentType : "application/json", dataType : "json",
        data:"id="+searchDeviceId(),    // beforeSend: function(xhr, settings) { if (!(/^(GET|HEAD|OPTIONS|TRACE|POST)$/.test(settings.type)) && !this.crossDomain) xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));},
        success:function (data) {
          try{
            var obj = eval('(' + data + ')');
            user_list_t = obj.user_list;
            $("#input_device_users").val(formatCheckedUserList(user_list_t));
          }catch(e){console.log("error GET user_list ", user_list_t);} 
        }
   });
});

user_list_t = null;
function formatCheckedUserList(userList){
    var str="";
    for(var uID in userList){
        var user = userList[uID];
        if(user.checked)
            str+=user.username+', ';
    }
    return str.slice(0,-2);
}

function dict2Url(dict){
    str = "";
     for(var key in dict){
        var item = dict[key];
        console.log(item);
        str+=key+"="+item.toString()+"&";
    }
    return str.slice(0,-1);
}

function onSaveSetting(){
    var new_data = new Object();
    new_data.device_node_id = setting_data.device_node_id.toString();// $("#input_device_id").val(searchDeviceId());    
    new_data.name = $("#input_device_name").val();
    new_data.type = $("#input_device_type").val()
    new_data.address = $("#input_device_address").val();
    new_data.second = Number($("#input_device_second").val());
    new_data.status = $("#input_device_state").val();
    new_data.description = getDescriptionString(setting_data.description);
    new_data.monitor_limit = getSensorListString(setting_data.monitor_limit);
    console.log("onSaveSetting",new_data);
    strURL = dict2Url(new_data);
    console.log(strURL);
    $.ajax({
        type: "POST",
        url: "/api/update_device_node/", // http://DESKTOP-T1J5L1V:80 data: JSON.stringify(json), contentType : "application/json", dataType : "json",
        data: strURL,    // beforeSend: function(xhr, settings) { if (!(/^(GET|HEAD|OPTIONS|TRACE|POST)$/.test(settings.type)) && !this.crossDomain) xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));},
        success:function (data) {
            dict = JSON.parse(data);
            alert(dict.code=="0"?"参数修改成功":JSON.stringify(dict));// unescape
            if(dict.code=="0")location.reload();          
        }
    });
}

function onSerachDevice() {
    var inputDevice  = $("#input_device_id").val()
    if(isNull(inputDevice))
        return;
    if(isNumber(inputDevice))        
        document.location = "/api/update_device_node/?device_node_id="+inputDevice+"&user_id="+searchUserId();
    
}

function onChangeUser(){
    if(user_list_t==null)return;    
    var isCheck = $("#sensor_setting_create_div").css("visibility") == "hidden" ? true:false;
    var tableHeight = getDictLength(user_list_t)*29+40+25;
    var strHeight = ""+tableHeight+"px"
    $("#sensor_setting_create_div").css("height",(isCheck?strHeight:"0px"));    
    $("#sensor_setting_create_div").css("visibility", (isCheck?"visible":"hidden"));  
    if(isCheck){
        loadAssign_device(user_list_t);
    }
}

function setSensor_list(sensor_list_t){
    $("#table_sensor_list tr:not(:first)").empty();    
    var sensor_list = eval('('+sensor_list_t+')');   
    function str2td(str_label_id, n){
        return "<input id="+str_label_id+" value="+n.toString()+">"
    }
    for(var key in sensor_list){
        var item = sensor_list[key];
        var name=key;var min=item[0];var max=item[1]; var unit=item[2];
        var str = "<tr><td>"+name+"</td><td>"+str2td("input_"+name+"_min",min)+"</td><td>"+str2td("input_"+name+"_max",max)+"</td><td>"+str2td("input_"+name+"_unit",unit)+"</td></tr>"
        $("#table_sensor_list").append(str)
    }
}

function getSensorListString(sensor_list_t){
    var sensor_list = eval('('+sensor_list_t+')');
    for(var key in sensor_list){
        var item = sensor_list[key];
        var id_min="#input_"+key+"_min";
        var id_max="#input_"+key+"_max";
        var id_unit="#input_"+key+"_unit";
        item[0] = parseInt($(id_min).val());
        item[1] = parseInt($(id_max).val());
        item[2] = $(id_unit).val();
    }
    return JSON.stringify(sensor_list);
}

function setDescription(description_data_t){ // "description": "{\"TriggerLevel0\":1,\"TriggerLevel1\":2,\"TriggerLevel2\":3,\"nSampleLen\":32768,\"nDelayCount\":-6000}"
    if(description_data_t == null || description_data_t.length<1){alert("description字段不是预期的数据格式"); return;}  
    try{
        var description_data = eval('('+description_data_t+')');
        if(description_data == null) {alert("description字段不是预期的数据格式"); return;}
        // $("#input_argument_sample_rate").val(20000);
        $("#input_argument_data_length").val(description_data.nSampleLen);
        $("#input_argument_data_late").val(description_data.nDelayCount);
        $("#input_argument_triglevel_x").val(description_data.TriggerLevel0);
        $("#input_argument_triglevel_y").val(description_data.TriggerLevel1);
        $("#input_argument_triglevel_z").val(description_data.TriggerLevel2); 
    }catch(e){alert("error setDescription", e);}
}

function getDescriptionString(description_data_t){
    // if(description_data_t == null || description_data_t.length<10) return description_data_t;
    // var description_data = eval('('+description_data_t+')');
    var description_data = new Object();
    description_data.nSampleLen = Number($("#input_argument_data_length").val());
    description_data.nDelayCount = Number($("#input_argument_data_late").val());
    description_data.TriggerLevel0 = Number($("#input_argument_triglevel_x").val());
    description_data.TriggerLevel1 = Number($("#input_argument_triglevel_y").val());
    description_data.TriggerLevel2 = Number($("#input_argument_triglevel_z").val()); 
    return JSON.stringify(description_data)
}